from .send_msg import *
from .grow_grass import *
from .systemInfo import *
from .HZYSS import *

import urllib.parse
import IPy
import json
import time

unknown_request_warning_state = False

class command_and_md():
    def __init__(self, req_data, NONE_REQ_DATA=False):
        if not NONE_REQ_DATA:
            self.req_data = self.webhook_url = self.senderid = self.text_info = self.sendernick = self.cmd = self.md_cmd = None
            self.changeReqData(req_data)

    def changeReqData(self, req_data):
        self.req_data = req_data
        self.webhook_url = req_data['sessionWebhook']
        self.senderid = req_data['senderId']
        self.text_info = req_data['text']['content'].strip()
        self.sendernick = req_data['senderNick']

        temp_text_info = self.text_info
        self.text_info = self.text_info.replace("\$", "__GOOD~ROBOT-LZG=DOLLAR+CMD>SPLIT?SIGN__")
        self.cmd = self.text_info.split("$")
        for i in range(len(self.cmd)):
            self.cmd[i] = self.cmd[i].replace("__GOOD~ROBOT-LZG=DOLLAR+CMD>SPLIT?SIGN__", "$")
        self.text_info = temp_text_info

        self.md_cmd = self.text_info.split("$")

        self.Banned_list = []
        with open("data/Banned.json", 'r') as f:
            self.Banned_list = json.load(f)

        self.Banned_ips_list = []
        with open("data/Banned_ips.json", 'r') as f:
            self.Banned_ips_list = json.load(f)
        with open("data/all_cmds.json", 'r') as f:
            self.c = json.load(f)

    '''
    Command部分
    '''

    def help(self):
        send_link_msg("帮助信息", "机器人帮助信息",
                      "https://gitee.com/lzg114514/GOOD_ROBOT_LZG/blob/master/command_help.md", self.webhook_url)

    def division_by_zero(self):
        # 用于测试错误捕捉功能
        a = 1 / 0

    def unknown_request_warning(self):
        global unknown_request_warning_state
        if self.cmd[2].lower() in ["t", "true"]:
            unknown_request_warning_state = True
            send_text_msg("未知请求警告功能已开启", self.webhook_url)
        elif self.cmd[2].lower() in ["f", "false"]:
            unknown_request_warning_state = False
            send_text_msg("未知请求警告功能已关闭", self.webhook_url)
        else:
            send_text_msg(f"错误的参数: {self.cmd[2]}\n启动: t / true\n关闭: f / false", self.webhook_url)

    def addref(self):
        self.c[self.cmd[2]] = self.cmd[3]
        with open("data/all_cmds.json", 'w') as f:
            json.dump(self.c, f)
        send_text_msg("已添加文本回复: " + self.cmd[2], self.webhook_url)

    def delref(self):
        self.c.pop(self.cmd[2])
        with open("data/all_cmds.json", 'w') as f:
            json.dump(self.c, f)
        send_text_msg("已删除文本回复: " + self.cmd[2], self.webhook_url)

    def ref(self):
        send_text_msg(json.dumps(self.c, indent=4), self.webhook_url)

    def runservercommand(self):
        input_password = self.cmd[2]
        cmd = self.cmd[3]

        password_sha256 = "d9328a22450deeeee7baab0d3f06f2a3511acab58adc3f424ed4bd2d75174bbe"
        if hashlib.sha256(input_password.encode('utf-8')).hexdigest() == password_sha256:
            os.system(cmd)
            send_text_msg("已执行CMD命令  " + cmd, self.webhook_url)
        else:
            send_text_msg("密码错误", self.webhook_url)

    def SystemInfo(self):
        info = json.dumps(GetFullSystemData(), indent=len(GetFullSystemData()))
        send_text_msg(info, self.webhook_url)

    def miniSystemInfo(self):
        cpu = GetCpuInfo()
        mem = GetMemInfoWindows()
        msg = "CPU : " + str(cpu['used']) + "%\n"
        msg += "内存 : " + str(round((mem['memRealUsed'] / mem['memTotal']) * 100, 2)) + "% (" + str(
            mem['memRealUsed']) + "/" + str(mem['memTotal']) + ")"
        send_text_msg(msg, self.webhook_url)

    def ban(self):
        if self.cmd[2] in self.Banned_list:
            send_text_msg(f"用户 \"{self.cmd[2]}\" 已经被封禁", self.webhook_url)
            return
        with open("data/Banned.json", 'w') as f:
            self.Banned_list.append(self.cmd[2])
            json.dump(self.Banned_list, f)
        send_text_msg("已封禁用户: " + self.cmd[2], self.webhook_url)

    def pardon(self):
        if self.cmd[2] in self.Banned_list:
            self.Banned_list.remove(self.cmd[2])
            with open("data/Banned.json", 'w') as f:
                json.dump(self.Banned_list, f)
            send_text_msg("已解除封禁用户: " + self.cmd[2], self.webhook_url)
        else:
            send_text_msg("用户 \"" + self.cmd[2] + "\" 没有被封禁", self.webhook_url)

    def banned_list(self):
        send_text_msg(json.dumps(self.Banned_list, indent=4, ensure_ascii=False), self.webhook_url)

    def bomb(self):
        WYT01_senderid = "$:LWCP_v1:$7GmjuWCt1XKzIqrIwFO8aoI85NS4CaFv"
        WYT02_senderid = "$:LWCP_v1:$tBsB6NcpnMfjyiblX4aR4gqyLXTPeFNQ"
        if self.senderid == WYT01_senderid or self.senderid == WYT02_senderid:
            send_text_msg("对于WYT，我们禁用了他的BOMB权限。", self.webhook_url)
            return
        try:
            bomb = int(self.cmd[2])
        except ValueError as e:
            send_text_msg("输入的数必须可以转化为整数", self.webhook_url)
            return
        if bomb <= 0:
            send_text_msg("参数必须大于等于0", self.webhook_url)
            return

        send_text_msg("Bomb Warning", self.webhook_url)
        for i in [3, 2, 1]:
            send_text_msg(i, self.webhook_url)
            time.sleep(1)

        for i in range(bomb):
            send_md_msg("BOMB",
                        "[![echo_img](http://pic.uzzf.com/up/2018-5/201805091154525122038.png)](http://www.homo.com/)<br>***卧*他*了个臭*啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊这帮没*的傻*玩意我*了踏马啊啊啊啊啊啊啊啊啊啊啊啊啊*** \n<br>\n# 谁挖的坑啊啊啊啊啊啊啊啊啊",
                        self.webhook_url)
            time.sleep(0.3)

    def grow_grass(self):
        s = self.cmd[2]
        try:
            times = int(self.cmd[3])
        except Exception:
            send_text_msg("参数必须可以使用int()函数转化为整数", self.webhook_url)
            return

        out = ""
        for i in range(times):
            out += grow_grass(s) + "\n"

        send_text_msg(out, self.webhook_url)

    def gui_jiao(self):
        text = self.cmd[2]
        id = gui_jiao.HZYSS_func(text)

        encode_url = urllib.parse.quote_plus("http://180.166.0.98:1458/guijiao?id=" + id)
        URL_ding = "dingtalk://dingtalkclient/page/link?url=" + encode_url + "&pc_slide=true"  # 钉钉内部打开的链接
        URL_web = "dingtalk://dingtalkclient/page/link?url=" + encode_url + "&pc_slide=false"  # 浏览器打开的链接
        send_actionCard_msg("播放", "# 点击按钮播放/下载音频", [getActionCardBtnData("钉钉内播放音频", URL_ding),
                                                                getActionCardBtnData("浏览器下载音频", URL_web)],
                            self.webhook_url)

    def getFileFromMediaId(self):
        media_id = self.cmd[2]
        file_type = self.cmd[3]
        expanded_name = self.cmd[4]

        file_name = "result_" + time.ctime().replace(" ", "_").replace(":", "@") + "_" + str(
            random.randint(1, 1000)) + "." + expanded_name
        send_file_msg(media_id, file_type, file_name, self.webhook_url)

    def ban_ip(self):
        if self.cmd[2] in self.Banned_ips_list:
            send_text_msg(f"IP \"{self.cmd[2]}\" 已经被封禁", self.webhook_url)
            return
        # 判断ip是否合法
        try:
            IPy.IP(self.cmd[2])
        except Exception:
            send_text_msg(f"{self.cmd[2]} 不是一个合法的IP地址", self.webhook_url)
            return
        with open("data/Banned_ips.json", 'w') as f:
            self.Banned_ips_list.append(self.cmd[2])
            json.dump(self.Banned_ips_list, f)
        send_text_msg("已封禁IP: " + self.cmd[2], self.webhook_url)

    def pardon_ip(self):
        # 判断ip是否合法
        try:
            IPy.IP(self.cmd[2])
        except Exception:
            send_text_msg(f"{self.cmd[2]} 不是一个合法的IP地址.", self.webhook_url)
            return
        if self.cmd[2] in self.Banned_ips_list:
            self.Banned_ips_list.remove(self.cmd[2])
            with open("data/Banned_ips.json", 'w') as f:
                json.dump(self.Banned_ips_list, f)
            send_text_msg("已解除封禁IP: " + self.cmd[2], self.webhook_url)
        else:
            send_text_msg(f"IP {self.cmd[2]} 没有被封禁", self.webhook_url)

    def banned_ip_list(self):
        if "" in self.Banned_ips_list:
            self.Banned_ips_list.remove("")
        send_text_msg(json.dumps(self.Banned_ips_list, indent=1, ensure_ascii=False), self.webhook_url)

    def raiseerror(self):
        raise Exception(self.cmd[2])

    def sayText(self):
        send_text_msg(self.cmd[2], self.webhook_url)

    def sayMd(self):
        send_md_msg("MD", self.cmd[2], self.webhook_url)

    '''
    Markdown部分
    '''

    def add(self):
        with open(f"./markdown/{self.cmd[3]}.md", 'a+') as f:
            f.truncate(0)
            f.write(self.cmd[4])
        send_text_msg(f"已添加Markdown回复: {self.cmd[3]}", self.webhook_url)

    def del_(self):
        if os.path.exists(f"./markdown/{self.cmd[3]}.md"):
            os.remove(f"./markdown/{self.cmd[3]}.md")
            send_text_msg(f"已删除Markdown回复: {self.cmd[3]}", self.webhook_url)
        else:
            send_text_msg(f"不存在此回复: {self.cmd[3]}", self.webhook_url)

    def delall(self):
        os.system("del markdown\\*.md")
        send_text_msg("已删除所有Markdown回复", self.webhook_url)

    def mdref(self):
        send_text_msg('请稍候...', self.webhook_url)
        msg_mdRefList = os.listdir("./markdown")
        MdRefDict = {}
        RefMsg = ''
        for mdRef in msg_mdRefList:
            tmp_mdref = ""
            with open(f"./markdown/{mdRef}") as f:
                tmp_mdref = f.read()
            mdRef = mdRef[:-3]
            MdRefDict[mdRef] = tmp_mdref
        if not MdRefDict:
            send_text_msg("No Ref!!!", self.webhook_url)
        else:
            for index, value in MdRefDict.items():
                RefMsg += f"<font color=#FF000>{index}</font>  :\n\n"
                RefMsg += value + "\n\n"
            send_md_msg('回复', RefMsg, self.webhook_url)
